昨天提到了Spring data JPA的好處跟 @Repository的宣告,今天我們就來幫大家整理一下JPA常用的語法吧!
以下我們都會用原生SQL搭配介紹
List<Book> findAll();
// SQL : Select * from Book;
Book findBookByBookId(Integer bookId);
/* SQL : Select * from Book where bookId = ? */
Book findBookByBooIdAndName(Integer bookId, String name);
/* SQL : Select * from Book where bookId = ? and name = ? */
Book findBookByBooIdOrName(Integer bookId, String name);
/* SQL : Select * from Book where bookId = ? or name = ? */
Book findBookByBooIdIsNull();
/* SQL : Select * from Book where bookId is null/
IsNotNull:等同於 SQL 中的 "is not null"
Like:等同於 SQL中的 "like",用法如下 👇
List<Book> findBookByNameLike(String name);
/* SQL : Select * from Book where name like '%?%'/
List<Book> findBookByBookIdIn(List<Integer> bookIds);
/* SQL : Select * from Book where bookId in (?)/
你也可使用原生的語法 @Query
@Query
裡面要第一個參數註明是 nativeQuery = true
接著後面就可以下SQL語法了 !!!!
@Query(nativeQuery = true, value = "select * from book where book_id = :bookId")
Book findBookByBookId(@Param("bookId") Integer bookId);
這樣有沒有發現Spring data JPA真的很方便呢